from watchdog.observers import Observer
from watchdog.events import *
import time

log_buff=""


def create_log_file_and_write():
    log_file = open("/home/Codes/python/aligo/log.txt","a+")
    log_file.write(log_buff)
    log_file.close()


class FileEventHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    """ def on_moved(self, event):
        if event.is_directory:
            print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))
        else:
            print("file moved from {0} to {1}".format(event.src_path,event.dest_path)) """

    def on_created(self, event):
        if event.is_directory:
            print("directory created:{0}".format(event.src_path),time.ctime())
            log_buff = "directory created:{0}".format(event.src_path)+' '+time.ctime()+'\n'
        else:
            print("file created:{0}".format(event.src_path),time.ctime())
            log_buff = "file created:{0}".format(event.src_path)+' '+time.ctime()+'\n'
        create_log_file_and_write()


    def on_deleted(self, event):
        if event.is_directory:
            print("directory deleted:{0}".format(event.src_path),time.ctime())
            log_buff = "directory deleted:{0}".format(event.src_path)+' '+time.ctime()+'\n'
        else:
            print("file deleted:{0}".format(event.src_path),time.ctime())
            log_buff = "file deleted:{0}".format(event.src_path)+' '+time.ctime()+'\n'
        create_log_file_and_write()


    """ def on_modified(self, event):
        if event.is_directory:
            print("directory modified:{0}".format(event.src_path))
        else:
            print("file modified:{0}".format(event.src_path)) """


if __name__ == "__main__":
    observer = Observer()
    event_handler = FileEventHandler()
    observer.schedule(event_handler,"/home/Codes/python/aligo/test",True)
    observer.start()
    # create_log_file_and_write()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()